package com.maon.mall.security.service;

import com.mano.mall.api.dto.member.output.UserOutputDTO;
import com.mano.mall.common.base.BaseResponse;
import com.maon.mall.security.feign.MemberServiceFeign;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceDetail implements UserDetailsService {

    @Autowired
    private MemberServiceFeign memberServiceFeign;


    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        BaseResponse<UserOutputDTO> userOutputDTOBaseResponse = memberServiceFeign.existMobile(userName);
        UserOutputDTO data = userOutputDTOBaseResponse.getData();
        String passWord = data.getPassWord();
        short is_avalible = data.getIs_avalible(); // 是否可用
        List<GrantedAuthority> role_user = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
        // 使用Spring Security UserDetailService 的内部类 User 创建user对象
        UserDetails userDetails = User.builder()
                .username(userName)
                .password(passWord)
                .disabled(BooleanUtils.toBoolean(is_avalible))
                .accountExpired(false)
                .accountLocked(false)
                .authorities(role_user).build();


        return userDetails;
    }
}
